package stu.edu.InterviewQuestion;

/**
 * Z字形排列
 */
public class ZigConversion {

    public static void main(String[] args) {
        String origin = "abcdefghijklmn";
        int numRows = 4;

        System.out.println(convert(origin, numRows));
    }

    /**
     * 转换Z型字符串
     * @param origin
     * @param numRows
     * @return
     */
    public static String convert(String origin, int numRows) {

        if (numRows == 1 || origin.length() <= numRows) {
            return origin;
        }
        StringBuilder[] sbArr = new StringBuilder[numRows];
        for (int i = 0; i < sbArr.length; i++) {
            sbArr[i] = new StringBuilder();
        }
        int idx = 0;
        int step = 1;
        for (int i = 0; i < origin.length(); i++) {
            sbArr[idx].append(origin.charAt(i));
            if (idx == 0) {
                step = 1;
            }
            if (idx == numRows - 1) {
                step = -1;
            }
            idx += step;
        }
        String res = "";
        for (int i = 0; i < sbArr.length; i++) {
            res += sbArr[i];
        }
        return res;
    }

}
